<?php

namespace app\common\business;

use app\common\lib\Str;
use app\common\lib\Time;
use app\common\model\mysql\User as UserModel;
use think\Exception;

class User
{

    public $userOBj = null;

    public function __construct()
    {
        $this->userOBj = new UserModel;
    }

    public function login($data)
    {
        $redisCode = cache(config("redis.code_pre").$data['phone_number']);
        if (empty($redisCode) || $redisCode != $data['code']) {
            throw new Exception("不存在该验证码");
        }
        $user = $this->userOBj->getUserByPhoneNumber($data['phone_number']);
        if (!$user) {
            $username = rand(1000,9999).'_'.$data['phone_number'];

            $userData = [
                'username' => $username,
                'phone_number' => $data['phone_number'],
                'type' => $data['type'],
                'status' => config('status.mysql.table_normal')
            ];
            try {
                $this->userOBj->save($userData);
                $userId = $this->userOBj->id;
            } catch (\Exception $e) {
                throw new Exception("数据库内部异常");
            }
        } else {
            //如果存在，更新数据
            $userData = [
                'login_ip' => request()->ip(),
                'operate_user' => $user['username'],
                'update_time' => time(),
            ];
            try {
                $userId = $user->id;
                $username = $user->username;
                $this->userOBj->updateById($userId, $userData);
            } catch (\Exception $e) {
                throw new Exception("数据库内部异常");
            }
        }
        $token = Str::getLoginToken($data['phone_number']);

        $redisData = [
            'id' => $userId,
            'username' => $username,
        ];
        $expireTime = Time::userLoginExpireTime($user['type']);

        $result = cache(config("redis.token_pre").$token, $redisData, $expireTime);
        return $result ? ['token' => $token, 'username' => $username] : false;
    }

    public function getNormalUserById($id)
    {
        $user = $this->userOBj->getUserById($id);
        if (!$user || $user['status'] != config("status.mysql.table_normal")) {
            return [];
        }
        return $user->toArray();

    }

    public function update($id, $data, $access_token)
    {
        // 检查用户是否存在
        $user = $this->userOBj->getUserById($id);
        if (!$user) {
            throw new Exception("不存在该用户");
        }
        // 检查用户名是否存在
        $userRes = $this->userOBj->getNormalUserByUsername($data['username']);
        if ($userRes && $userRes['id'] != $id) {
            throw new Exception("该用户已存在，请重试");
        }
        
        // 用户名被修改，redis 数据需要同步下
        $redisData = [
            'id' => $id,
            'username' => $data['username']
        ];
        cache(config("redis.token_pre").$access_token, $redisData);

        return $this->userOBj->updateById($id, $data);;

    }

}